import React, { useState, useEffect, useCallback } from "react";
import { useRequest } from "ahooks";

function usePolling(
  requestId: string | null,
  pollingAPI: (id: string) => Promise<any>
) {
  const [data, setData] = useState<any>(null);
  const [isPolling, setIsPolling] = useState<boolean>(false);

  const startPolling = useCallback(() => {
    if (!requestId) return;

    setIsPolling(true);
    const intervalId = setInterval(async () => {
      const result = await pollingAPI(requestId);
      if (result !== null) {
        setData(result);
        clearInterval(intervalId);
        setIsPolling(false);
      }
    }, 3000);

    return () => clearInterval(intervalId);
  }, [requestId, pollingAPI]);

  useEffect(() => {
    if (requestId) {
      const stopPolling = startPolling();
      return stopPolling;
    }
  }, [requestId, startPolling]);

  return { data, isPolling };
}

const ImgSelection = () => {
  const [requestId, setRequestId] = React.useState<string | null>(null);

  // 提交操作
  const submit = async () => {
    // 假设submitAPI是一个返回requestId的异步函数
    const response = await submitAPI();
    setRequestId(response.requestId);
  };

  const { data, isPolling } = usePolling(requestId, pollingAPI);

  return (
    <div>
      <button onClick={submit}>提交</button>
      <div>任务状态: {isPolling ? "轮询中..." : JSON.stringify(data)}</div>
    </div>
  );
};

export default ImgSelection;
